﻿namespace nhCore.Modbus;

/// <summary>
/// 气象数据解析器类，解析实时、历史数据
/// </summary>
public class WeatherAnalyzer : Analyzer
{
    public WeatherAnalyzer()
    {
        Name = "气象数据解析器";
        Decoders = [];
    }

    public override object Analysis(object o)
    {
        List<Weathers> listWeathers = [];
        if (o is not byte[] byts) { return listWeathers; }
        FrameValid mb = new(byts, true);
        int index;
        byte addr;
        Weathers ws;
        //一条命令可能映射到多个站点
        var groups = Decoders.Where(x => x.ElementConfig.RegAddress != CoreGlobal.Const_TimeIndex).GroupBy(x => x.ElementConfig.MappingStationId).ToList();
        Decoder timeDecoder = Decoders.Single(x => x.ElementConfig.RegAddress == CoreGlobal.Const_TimeIndex);
        foreach (var group in groups.ToList())
        {
            addr = group.Key;
            ws = RealData.Singleton.FindOrAddWeathers(addr);
            List<Decoder> listDecoder = [.. group];
            listDecoder.Add(timeDecoder);
            foreach (Decoder d in listDecoder)
            {
                if (d is not CgqTimeDecoder && d.ElementConfig.DeviceAddress == 0) { continue; }
                Weather w = new()
                {
                    Config = d.ElementConfig,
                };

                index = w.Config.RegAddress;

                w.Value = d.DeCode(mb);
                w.StrValue = w.Value.HasValue ? d.Convert(w.Value.Value) : "-";

                Int16 reg = d.ElementConfig.StationReg;
                ws.AddValue(reg, w);//时间为index为-1，传感器数据也可能为0
            }
            if (ws.Values.Count > 0)
            {
                listWeathers.Add(ws);
            }
        }
        return listWeathers;
    }
}
